﻿#include "cacheapi.h"
#include <QDateTime>


CacheApi::CacheApi()
{

}

CacheApi* CacheApi::instance(){
    return cacheInstance();  // 返回线程安全的静态对象
}


void CacheApi::insert(QString key, QString value, int expiredSec)
{
    long nowSesc = QDateTime::currentMSecsSinceEpoch() / 1000;
    mapValue[key] = value;
    mapExpired[key] = nowSesc + expiredSec;
}

void CacheApi::remove(QString key)
{
    if(!mapValue.contains(key))
        mapValue.remove(key);
    if(!mapExpired.contains(key))
        mapExpired.remove(key);
}

QString CacheApi::get(QString key)
{
    //检查是否存在
    if(!mapValue.contains(key))
        return NULL;
    if(!mapExpired.contains(key))
        return NULL;

    //检查是否失效
    long nowSesc = QDateTime::currentDateTime().currentMSecsSinceEpoch() / 1000;
    if(mapExpired[key] <= nowSesc)
    {
        mapValue.remove(key);
        mapExpired.remove(key);
        return NULL;
    }
    return mapValue[key];
}
